from pydantic_settings import BaseSettings
from enum import Enum
from pathlib import Path
from urllib.parse import quote_plus

# 获取项目根目录
ROOT_DIR = Path(__file__).parent.parent.parent
ENV_FILE = ROOT_DIR / ".env"

class ServiceType(str, Enum):
    DEEPSEEK = "deepseek"
    OLLAMA = "ollama"
    QWEN = "qwen"
    KIMI = "kimi"
    GLM = "glm"

class Settings(BaseSettings):
    # Server settings
    SERVICE_NAME: str
    # Logging settings
    LOG_LEVEL: str = "DEBUG"  # 日志级别：DEBUG, INFO, WARNING, ERROR, CRITICAL
    
    # Deepseek settings
    DEEPSEEK_API_KEY: str
    DEEPSEEK_BASE_URL: str
    DEEPSEEK_MODEL: str
    
    # Vision Model settings (独立配置)
    VISION_API_KEY: str
    VISION_BASE_URL: str
    VISION_MODEL: str
    
    # Ollama settings
    OLLAMA_BASE_URL: str = "http://localhost:11434"
    OLLAMA_CHAT_MODEL: str = ""
    OLLAMA_REASON_MODEL: str = ""
    OLLAMA_EMBEDDING_MODEL: str = "bge-m3:latest"
    OLLAMA_AGENT_MODEL: str = ""
    OLLAMA_RERANK_MODEL: str = "bge-rerank:q8"
    
    # DashScope (Qwen) settings
    DASHSCOPE_API_KEY: str = ""
    DASHSCOPE_BASE_URL: str = "https://dashscope.aliyuncs.com/compatible-mode/v1"
    DASHSCOPE_MODEL: str = "qwen-plus"
    DASHSCOPE_FINANCE_MODEL: str = "Tongyi-Finance-14B-Chat"  # Qwen Finance模型名称
    
    # Moonshot (Kimi) settings
    MOONSHOT_API_KEY: str = ""
    MOONSHOT_BASE_URL: str = "https://api.moonshot.cn/v1"
    MOONSHOT_MODEL: str = "moonshot-v1-8k"
    
    # Zhipu (GLM) settings
    ZHIPU_API_KEY: str = ""
    ZHIPU_BASE_URL: str = "https://open.bigmodel.cn/api/paas/v4/"
    ZHIPU_MODEL: str = "glm-4.5"
    # Service selection
    CHAT_SERVICE: ServiceType = ServiceType.OLLAMA
    REASON_SERVICE: ServiceType = ServiceType.OLLAMA
    AGENT_SERVICE: ServiceType = ServiceType.OLLAMA
    
    # Search settings
    SERPAPI_KEY: str = ""  # 设置默认值
    SEARCH_RESULT_COUNT: int = 3
    
    # Database settings
    DB_HOST: str
    DB_PORT: int
    DB_USER: str
    DB_PASSWORD: str
    DB_NAME: str
    
    # JWT settings
    SECRET_KEY: str = "your-secret-key"  # 在生产环境中使用安全的密钥
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    
    # Embedding settings 
    EMBEDDING_TYPE: str = "ollama"  # ollama, huggingface, openai 或 custom
    EMBEDDING_MODEL: str = "bge-m3:latest"  # 嵌入模型名称
    EMBEDDING_API_BASE: str = "http://direct.virtaicloud.com:45608/v1/embeddings"  # 自搭建嵌入服务地址（当使用custom类型时）
    EMBEDDING_API_KEY: str = "EMPTY"  # 嵌入服务API密钥（当使用custom类型时）
    EMBEDDING_THRESHOLD: float = 0.90  # 语义相似度阈值
    EMBEDDING_DIM: int = 1024  # 嵌入向量维度
    
    # Chroma settings
    CHROMA_HOST: str = "localhost"
    CHROMA_PORT: int = 8002
    
    # 向量数据库配置
    VECTOR_DB_PROVIDER: str = "milvus"
    
    # Chroma 配置
    CHROMA_COLLECTION_NAME: str = "knowledge_base"
    
    # 向量存储类型配置
    VECTOR_STORE_TYPE: str = "milvus"

    # Milvus 配置
    MILVUS_HOST: str = "localhost"
    MILVUS_PORT: str = "19530"
    MILVUS_COLLECTION_NAME: str = "knowledge_cleaned"
    MILVUS_USERNAME: str = ""
    MILVUS_PASSWORD: str = ""
    
    # PDF文本文件根目录
    PDF_TXT_FILE_ROOT: str = str(ROOT_DIR.parent / "dataset" / "pdf_txt_file_my")
    
    # RAG settings
    CHUNK_SIZE: int = 800
    CHUNK_OVERLAP: int = 100
    
    # Email settings
    EMAIL_ENABLED: bool = False
    EMAIL_HOST: str = ""
    EMAIL_PORT: int = 587
    EMAIL_USERNAME: str = ""
    EMAIL_PASSWORD: str = ""
    EMAIL_FROM_ADDRESS: str = ""
    EMAIL_FROM_NAME: str = "RAGent Platform"
    EMAIL_USE_TLS: bool = True
    
    @property
    def DATABASE_URL(self) -> str:
        # 对密码进行URL编码，解决包含特殊字符（如@）的问题
        encoded_password = quote_plus(self.DB_PASSWORD)
        return f"mysql+aiomysql://{self.DB_USER}:{encoded_password}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"
    
    class Config:
        env_file = str(ENV_FILE)  # 使用绝对路径
        env_file_encoding = "utf-8"
        case_sensitive = True

settings = Settings()

